/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.sumofseries.utilconcurrent;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 *
 * @author Neophron
 */
public class Sum {

    public static final double STEP = 0.0001;

    public static double sum(int from, int to, int numberOfThreads)
            throws Exception {
        double part = (to - from) * 1.0 / numberOfThreads;
        ExecutorService exec = Executors.newFixedThreadPool(numberOfThreads);
        ArrayList<Future<Double>> result = new ArrayList<>();
        for (int i = 0; i < numberOfThreads; i++) {
            double tfrom = from + part * i;
            double tto = from + part * (i + 1);
            result.add(exec.submit(new Calc(tfrom, tto)));
        }
        double res = 0;
        for (int i = 0; i < result.size(); i++) {
            res += result.get(i).get();
        }
        return res;
    }

}
